namespace RBAC.Write.Api.Application.Handler.QualityHandler
{
    using MediatR;
    using Microsoft.Extensions.Logging;
    using RBAC.Domain.QualityManage;
    using RBAC.ErrorCode;
    using RBAC.Interstructrue.Base;
    using RBAC.Write.Api.Application.Command.QualityCommand;

    /// <summary>
    /// 删除质量工单 处理器（软删除）。
    /// </summary>
    /// <remarks>
    /// 主要逻辑：
    /// 1. 校验 <c>Id</c> > 0，并查询未删除实体。
    /// 2. 执行软删除：设置 <c>IsDeleted = true</c> 并更新。
    /// 3. rows > 0 视为成功，统一日志与异常处理。
    /// </remarks>
    /// </summary>
    public class QualityOrderDeleteHandler : IRequestHandler<QualityOrderDeleteCommand, APIResult<int>>
    {
        private readonly IBaseRepository<QualityOrder> _orderRepo;
        private readonly ILogger<QualityOrderDeleteHandler> _logger;

        public QualityOrderDeleteHandler(IBaseRepository<QualityOrder> orderRepo, ILogger<QualityOrderDeleteHandler> logger)
        {
            _orderRepo = orderRepo;
            _logger = logger;
        }

        /// <summary>
        /// 处理“删除质量工单（软删除）”请求。
        /// </summary>
        /// <param name="request">删除命令，包含工单 Id。</param>
        /// <param name="cancellationToken">取消令牌。</param>
        /// <returns>返回受影响行数的 <see cref="APIResult{T}"/>。</returns>
        public Task<APIResult<int>> Handle(QualityOrderDeleteCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<int>();
            try
            {
                // 检查是否被取消
                cancellationToken.ThrowIfCancellationRequested();
                // 参数校验：Id 必须有效
                if (request.Id <= 0)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "Id无效", Data = 0 });

                // 查询未删除的目标实体
                var entity = _orderRepo.GetFirstOrDefault("Id = @Id AND IsDeleted = 0", new { Id = request.Id });
                if (entity == null)
                    return Task.FromResult(new APIResult<int> { Code = APIEnums.Fail, Msg = "质量工单不存在", Data = 0 });

                // 软删除标记并保存
                entity.IsDeleted = true;
                var rows = _orderRepo.Update(entity);

                // 返回语义：rows > 0 视为成功
                result.Code = rows > 0 ? APIEnums.Success : APIEnums.Fail;
                result.Msg = rows > 0 ? "删除质量工单成功" : "删除质量工单失败";
                result.Data = rows;
            }
            catch (OperationCanceledException)
            {
                // 捕获取消异常
                _logger?.LogWarning("删除质量工单被取消");
                result.Code = APIEnums.Fail;
                result.Msg = "请求已取消";
                result.Data = 0;
            }
            catch (Exception ex)
            {
                // 统一异常处理与日志
                _logger?.LogError(ex, "删除质量工单异常: {Message}", ex.Message);
                result.Code = APIEnums.Fail;
                result.Msg = "删除质量工单异常: " + ex.Message;
                result.Data = 0;
            }

            return Task.FromResult(result);
        }
    }
}
